<?php

namespace admin\modules\equipment_info\models;

use common\models\db\Equipment;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * EquipmentSearch represents the model behind the search form about `admin\modules\equipment_info\models\Equipment`.
 */
class EquipmentSearch extends Equipment
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'ram_size', 'rom_size', 'app_version_id'], 'integer'],
            [['uuid', 'os_type', 'name', 'brand', 'model', 'system', 'system_version', 'kernel_version', 'hardware_version', 'cpu', 'last_app_use_at'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Equipment::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'ram_size' => $this->ram_size,
            'rom_size' => $this->rom_size,
            'app_version_id' => $this->app_version_id,
//            'last_app_use_at' => $this->last_app_use_at,
        ]);

        $query->andFilterWhere(['like', 'uuid', $this->uuid])
            ->andFilterWhere(['like', 'os_type', $this->os_type])
            ->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'brand', $this->brand])
            ->andFilterWhere(['like', 'model', $this->model])
            ->andFilterWhere(['like', 'system', $this->system])
            ->andFilterWhere(['like', 'system_version', $this->system_version])
            ->andFilterWhere(['like', 'kernel_version', $this->kernel_version])
            ->andFilterWhere(['like', 'hardware_version', $this->hardware_version])
            ->andFilterWhere(['like', 'cpu', $this->cpu]);

        if ( ! is_null($this->last_app_use_at) && strpos($this->last_app_use_at, ' - ') !== false ) {
            list($start_date, $end_date) = explode(' - ', $this->last_app_use_at);
            $query->andFilterWhere(['between', 'last_app_use_at', strtotime($start_date), strtotime($end_date.' 23:59:59')]);
        }

        return $dataProvider;
    }
}
